//
//  GHDiaryDataHandle.m
//  Diary
//
//  Created by lanou3g on 15/11/3.
//  Copyright © 2015年 王艺拓. All rights reserved.
//

#import "GHDiaryDataHandle.h"
#import "DiaryEntity+CoreDataProperties.h"
#import "WYTEditingViewA.h"
#import "WYTTimeTool.h"
#import "GHDiaryDataModel.h"

@interface GHDiaryDataHandle ()

@property (nonatomic, retain) NSMutableArray *dataArray;

@end

@implementation GHDiaryDataHandle

- (void)saveDataWithManageContext:(NSManagedObjectContext *)manageContext
                     AndWithModel:(GHDiaryDataModel *)dataModel
{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:kEntity];
    NSEntityDescription *des = [NSEntityDescription entityForName:kEntity inManagedObjectContext:manageContext];
    request.entity = des;
    NSError *error = nil;
    self.dataArray = [[manageContext executeFetchRequest:request error:&error] mutableCopy];
    if (self.dataArray == nil) {
        //NSLog(@"存储失败");
    }
    switch (dataModel.clickTag.integerValue) {
        case 186010:
        {
            if ([dataModel.summary isEqualToString:@""]) {
                //NSLog(@"没有数据不能进行存储");
            } else {
                NSString *string = [self getSummaryStringWithInteger:dataModel AndWithManageContext:manageContext];
                //NSLog(@"--------------------------------- string = %@", string);
                
                NSString *pageID = [self getPageModelIDWithModel:dataModel AndWithManageContext:manageContext];
                //NSLog(@"================================== string = %@", pageID);
                if ([string isEqualToString:dataModel.summary] && [pageID isEqualToString:dataModel.clickTag]) {
                    //NSLog(@"该数据已经存储过了");
                } else {
                    DiaryEntity *entity = [NSEntityDescription insertNewObjectForEntityForName:kEntity inManagedObjectContext:manageContext];
                    // 模板ID
                    [entity setPageID:dataModel.clickTag];
                    // 个人ID
                    [entity setDiaryID:[NSString stringWithFormat:@"%@%@", dataModel.clickTag,[WYTTimeTool currentSystemDateString]]];
                    if (dataModel.photoImg != nil) {
                        // 图片
                        [entity setPhoto:dataModel.photoImg];
                    } else {
                        [entity setPhoto:@""];
                    }
                    // 标题
                    [entity setTitle:dataModel.title];
                    // 子标题
                    [entity setSubtitle:dataModel.subtitle];
                    // 内容
                    [entity setSummary:dataModel.summary];
                    // 日期
                    [entity setDateInfo:dataModel.dateLabelText];
                    // 地点
                    [entity setLocationInfo:dataModel.placeLabel];
                    // 日记图片
                    if (dataModel.diaryImage != nil) {
                        [entity setDiaryImage:dataModel.diaryImage];
                    } else {
                        [entity setDiaryImage:@""];
                    }
                    BOOL isSave = [manageContext save:&error];
                    if (isSave == NO) {
                        //NSLog(@"保存失败");
                    } else {
                        //NSLog(@"保存成功");
                    }
                }
            }
            break;
        }
        default:
            if (dataModel.photoImg == nil || [dataModel.title isEqualToString:@""]) {
                //NSLog(@"没有图片数据不能进行存储");
            } else {
                NSString *string = [self getTitleStringWithInteger:dataModel AndWithManageContext:manageContext];
                NSString *pageID = [self getPageModelIDWithModel:dataModel AndWithManageContext:manageContext];
                if ([string isEqualToString:dataModel.title] && [dataModel.clickTag isEqualToString:pageID]) {
                    //NSLog(@"带图片的数据的也已经存储过了");
                } else {
                    DiaryEntity *entity = [NSEntityDescription insertNewObjectForEntityForName:kEntity inManagedObjectContext:manageContext];
                    // 模板ID
                    [entity setPageID:dataModel.clickTag];
                    // 个人ID
                    [entity setDiaryID:[NSString stringWithFormat:@"%@%@", dataModel.clickTag,[WYTTimeTool currentSystemDateString]]];
                    if (dataModel.photoImg != nil) {
                        // 图片
                        [entity setPhoto:dataModel.photoImg];
                    } else {
                        [entity setPhoto:@""];
                    }
                    // 标题
                    [entity setTitle:dataModel.title];
                    // 子标题
                    [entity setSubtitle:dataModel.subtitle];
                    // 内容
                    [entity setSummary:dataModel.summary];
                    // 日期
                    [entity setDateInfo:dataModel.dateLabelText];
                    // 地点
                    [entity setLocationInfo:dataModel.placeLabel];
                    // 日记图片
                    if (dataModel.diaryImage != nil) {
                        [entity setDiaryImage:dataModel.diaryImage];
                    } else {
                        [entity setDiaryImage:@""];
                    }
                    BOOL isSave = [manageContext save:&error];
                    if (isSave == NO) {
                        //NSLog(@"保存失败");
                    } else {
                        //NSLog(@"保存成功");
                    }
                }
            }
            break;
    }
}

- (NSString *)getTitleStringWithInteger:(GHDiaryDataModel *)model AndWithManageContext:(NSManagedObjectContext *)manageContext
{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:kEntity];
    NSEntityDescription *des = [NSEntityDescription entityForName:kEntity inManagedObjectContext:manageContext];
    request.entity = des;
    
    if (model.title != nil) {
        NSPredicate *pre2 = [NSPredicate predicateWithFormat:@"title like %@", model.title];
        request.predicate = pre2;
    }
    NSArray *array = [manageContext executeFetchRequest:request error:nil];
    if (array == nil) {
        //NSLog(@"查询失败");
    }
    for (int i = 0; i < array.count; i++) {
        DiaryEntity *entity = array[i];
        if ([model.title isEqualToString:entity.title]) {
            return entity.title;
        }
    }
    return nil;
}

- (NSString *)getSummaryStringWithInteger:(GHDiaryDataModel *)model AndWithManageContext:(NSManagedObjectContext *)manageContext
{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:kEntity];
    NSEntityDescription *des = [NSEntityDescription entityForName:kEntity inManagedObjectContext:manageContext];
    request.entity = des;
    if (model.summary != nil) {
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"pageID like %@", model.clickTag];
        request.predicate = pre;
    }
    NSArray *array = [manageContext executeFetchRequest:request error:nil];
    if (array == nil) {
        //NSLog(@"查询失败");
    }
    for (int i = 0; i < array.count; i++) {
        DiaryEntity *entity = array[i];
        //NSLog(@"entity.summary = %@", entity.summary);
        //NSLog(@"model.summary = %@", model.summary);
        if ([model.summary isEqualToString:entity.summary]) {
            return model.summary;
        }
    }
    return nil;
}

// 返回Model的ID
- (NSString *)getPageModelIDWithModel:(GHDiaryDataModel *)model AndWithManageContext:(NSManagedObjectContext *)manageContext
{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:kEntity];
    NSEntityDescription *des = [NSEntityDescription entityForName:kEntity inManagedObjectContext:manageContext];
    request.entity = des;
    if (model.clickTag != nil) {
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"pageID like %@", model.clickTag];
        request.predicate= pre;
    }
    NSArray *array = [manageContext executeFetchRequest:request error:nil];
    if (array== nil) {
        //NSLog(@"查询ID失败");
    }
    for (DiaryEntity *entity in array) {
        if (entity.pageID == model.clickTag) {
            return entity.pageID;
        }
    }
    return nil;
}

// 获取截屏的图片数组
- (NSMutableArray *)getImagesWithManagedObjecContext:(NSManagedObjectContext *)manageContext
{
    NSMutableArray *arrayImage = [NSMutableArray array];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:kEntity];
    NSEntityDescription *des = [NSEntityDescription entityForName:kEntity inManagedObjectContext:manageContext];
    request.entity = des;
    NSArray *array = [manageContext executeFetchRequest:request error:nil];
    if (array.count > 0) {
        for (int i = 0; i < array.count; i++) {
            DiaryEntity *entity = array[i];
            if (entity.diaryImage != nil && ![entity.diaryImage isEqual:@""]) {
                [arrayImage addObject:entity.diaryImage];
            }
        }
    }
    return arrayImage;
}

// 获取Model的数组
- (NSMutableArray *)getModelArrayWithManagedObjectContext:(NSManagedObjectContext *)manageContext
{
    NSMutableArray *tmpArray = [NSMutableArray array];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:kEntity];
    NSEntityDescription *des = [NSEntityDescription entityForName:kEntity inManagedObjectContext:manageContext];
    request.entity = des;
    NSError *error = nil;
    NSArray *array = [manageContext executeFetchRequest:request error:&error];
    if (array.count > 0) {
        for (DiaryEntity *entity in array) {
            GHDiaryDataModel *dataModel = [[GHDiaryDataModel alloc] init];
            dataModel.clickTag = entity.pageID;
            dataModel.diaryID = entity.diaryID;
            dataModel.photoImg = entity.photo;
            dataModel.title = entity.title;
            dataModel.subtitle = entity.subtitle;
            dataModel.dateLabelText = entity.dateInfo;
            dataModel.placeLabel = entity.locationInfo;
            dataModel.diaryImage = entity.diaryImage;
            dataModel.summary = entity.summary;
            [tmpArray addObject:dataModel];
        }
    }
    return tmpArray;
}

// 删除指定的数据
- (void)deletModelWithMnagedObjectContext:(NSManagedObjectContext *)manageContext AndWithIndex:(NSInteger)index
{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:kEntity];
    NSEntityDescription *des = [NSEntityDescription entityForName:kEntity inManagedObjectContext:manageContext];
    request.entity = des;
    NSError *error = nil;
    NSArray *array = [manageContext executeFetchRequest:request error:&error];
    if (array.count > 0) {
        for (int i = 0; i < array.count; i++) {
            if (i == index) {
                DiaryEntity *entity = array[i];
                [manageContext deleteObject:entity];
            }
        }
    }
    BOOL isSave = [manageContext save:&error];
    if (isSave == YES) {
        //NSLog(@"删除数据成功");
    } else {
        //NSLog(@"删除数据失败");
    }
}

// 删除所有的数据
- (void)deletAllDataWithManageContext:(NSManagedObjectContext *)manageContext
{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:kEntity];
    NSEntityDescription *des = [NSEntityDescription entityForName:kEntity inManagedObjectContext:manageContext];
    request.entity = des;
    NSError *error = nil;
    NSArray *array = [manageContext executeFetchRequest:request error:&error];
    if (array.count > 0) {
        for (int i = 0;  i < array.count;  i++) {
            DiaryEntity *entity = array[i];
            [manageContext deleteObject:entity];
        }
    }
    BOOL isSave = [manageContext save:&error];
    if (isSave == YES) {
        //NSLog(@"删除所有数据成功");
    } else {
        //NSLog(@"删除所有数据失败");
    }
}

// Model的转换
- (GHDiaryDataModel *)getModelWithFZLModel:(FZLDiaryDataObject *)obj
{
    GHDiaryDataModel *model = [[GHDiaryDataModel alloc] init];
    model.diaryID = obj.diaryID;
    model.clickTag = obj.clickTag;
    NSData *da = [NSData dataWithContentsOfURL:[NSURL URLWithString:[obj.photoImg url]]];
    model.photoImg = [UIImage imageWithData:da];
    model.title = obj.title;
    model.subtitle = obj.subtitle;
    model.summary = obj.summary;
    model.dateLabelText = obj.dateLabelText;
    model.placeLabel = obj.placeLabel;
    NSData *daImg = [NSData dataWithContentsOfURL:[NSURL URLWithString:[obj.diaryImage url]]];
    model.diaryImage = [UIImage imageWithData:daImg];
    return model;
}

// 懒加载
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
